package com.jianggy.date;

import java.util.regex.Pattern;

/**
 * parse the given date variable and return the date format string,
 * in other word the program can automatically identify the date's formate
 *
 * @author jianggy
 * @version 1.0
 * @time 2019/7/3 11:38
 * @see
 **/
public class DateFormatUtils {
    public static void main(String[] args){
        String s = IdentifyDateFormat("2018-01-02 11:11:11.0");
       s = s.replace("HH","hh24");
       s = s.replace("mm","mi");

        System.out.println(s);
    }
    public static String IdentifyDateFormat(String date) {
        boolean year = false;
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        if (pattern.matcher(date.substring(0, 4)).matches()) {
            year = true;
        }
        StringBuilder sb = new StringBuilder();
        int index = 0;
        if (!year) {
            if (date.contains("月") || date.contains("-") || date.contains("/")) {
                if (Character.isDigit(date.charAt(0))) {
                    index = 1;
                }
            } else {
                index = 3;
            }
        }
        for (int i = 0; i < date.length(); i++) {
            char chr = date.charAt(i);
            if (Character.isDigit(chr)) {
                if (index == 0) {
                    sb.append("y");
                }
                if (index == 1) {
                    sb.append("M");
                }
                if (index == 2) {
                    sb.append("d");
                }
                if (index == 3) {
                    sb.append("H");
                }
                if (index == 4) {
                    sb.append("m");
                }
                if (index == 5) {
                    sb.append("s");
                }
                if (index == 6) {
                    // sb.append("S");
                    int p = sb.lastIndexOf(".");
                    sb.deleteCharAt(p);
                }
            } else {
                if (i > 0) {
                    char lastChar = date.charAt(i - 1);
                    if (Character.isDigit(lastChar)) {
                        index++;
                    }
                }
                sb.append(chr);
            }
        }
        return sb.toString();
    }

}
